<?php
/**
 */
class Yz_Action_SelectList
    extends Yz_Action_Select
{

    /** SQL rows limit
     *  @var null
     */
    protected $limit;

    /** SQL rows offset, default null (unused)
     *  @var null
     */
    protected $offset;

    /**
     *  @var bool
     */
    protected $calcFoundRows = false;

    /************************************
     *          Public methods          *
     ************************************/


    /**
     *  @param int $limit >= 0
     *  @return this
     */
    public function setLimit( $limit )
    {
        debug();
        $this->limit = Yz_Int::testNotNegative($limit);
        return $this;
    }

    /**
     *  @param int $offset >= 0
     *  @return this
     */
    public function setOffset( $offset )
    {
        debug();
        $this->offset = Yz_Int::testNotNegative($offset);
        return $this;
    }



    /**
     *  @return int
     */
    public function getFoundRows()
    {
        if (! $this->executed)
            throw new Yz_Action_Exception_NotExecutedYet();
        return $this->statement->getFoundRows();
    }

    /**
     *  @return Yz_Array
     */
    public function fetch()
    {
        if (! $this->executed)
            throw new Yz_Action_Exception_NotExecutedYet();
        $values = $this->statement->fetchAll();
        if (! $values)
            throw new Yz_Action_Exception_NoValues();
        return $this->bindResultList($values);
    }



    /************************************
     *        Protected methods         *
     ************************************/

    /** Verify any arguments before building query
     *      verify the offset/limit, set calcFoundRows if limit is set
     *  @return this
     */
    protected function verifyArguments()
    {
        debug();
        $this->calcFoundRows = !!$this->limit;
        return $this;
    }


    /**
     *  Apply the arguments to the SQL statement
     *      Setup limit to avoid occasional selection of all rows
     *  @param Yz_SQL_Statement $sql
     *  @return this
     */
    protected function applyArguments(Yz_SQL_Statement $sql)
    {
        debug();
        if ($this->limit)
            $sql
                ->calcFoundRows($this->calcFoundRows) // sensible only with limit
                ->limit($this->offset, $this->limit)
            ;
        return $this;
    }

    protected function bindResultList($values)
    {
        $out = array();
        foreach ($values as $v)
            $out[] = $this->bindResult($v);
        return $out;
    }

}
